//
// ArchiveStrategy.h
//
// $Id: //poco/1.4/Foundation/include/Poco/ArchiveStrategy.h#1 $
//
// Library: Foundation
// Package: Logging
// Module:  FileChannel
//
// Definition of the ArchiveStrategy class and subclasses.
//
// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#ifndef Foundation_ArchiveStrategy_INCLUDED
#define Foundation_ArchiveStrategy_INCLUDED


#include "Poco/Foundation.h"
#include "Format.h"
#include "Poco/File.h"
#include "Poco/LocalDateTime.h"
namespace Poco {


//class ArchiveCompressor;


class Foundation_API ArchiveStrategy
	/// The ArchiveStrategy is used by FileChannel 
	/// to rename a rotated log file for archiving.
	///
	/// Archived files can be automatically compressed,
	/// using the gzip file format.
{
public:
	ArchiveStrategy();
	virtual ~ArchiveStrategy();

	virtual string archive(const string& filepath) = 0;
		/// Renames the given log file for archiving
		/// and return the archived filename

	void compress(bool flag = true);
		/// Enables or disables compression of archived files.	

protected:
	void moveFile(const std::string& oldName, const std::string& newName);
	bool exists(const std::string& name);
	
private:
	ArchiveStrategy(const ArchiveStrategy&);
	ArchiveStrategy& operator = (const ArchiveStrategy&);
	
	bool                    m_compress;
	//ArchiveCompressor*      m_pCompressor;
};


class Foundation_API ArchiveByNumberStrategy: public ArchiveStrategy
	/// A monotonic increasing number is appended to the
	/// log file name. The most recent archived file
	/// always has the number zero.
{
public:
	ArchiveByNumberStrategy();
	~ArchiveByNumberStrategy();
	virtual string archive(const string& filepath);
};


template <class DT>
class ArchiveByTimestampStrategy: public ArchiveStrategy
	/// A timestamp (YYYYMMDDhhmmssiii) is appended to archived
	/// log files.
{
public:
	ArchiveByTimestampStrategy()
	{
	}
	
	~ArchiveByTimestampStrategy()
	{
	}
	
	virtual string archive(const string& filepath)
		/// Archives the file by appending the current timestamp to the
		/// file name. return the archived filename
	{
		std::string archPath = filepath;
		archPath.append(".");
		DT	dt;
		archPath+=format("%04d%02d%02d_%02d%02d%02d", dt.year(),dt.month(),dt.day(),dt.hour(),dt.minute(),dt.second());
		
		if (exists(archPath)) 
		{
			archPath = genFileNameByNumber(archPath);
			moveFile(filepath, archPath);
		}
		else moveFile(filepath, archPath);
		return archPath;
	}

private:
	string genFileNameByNumber(const std::string& basePath)
		/// A monotonic increasing number is appended to the
		/// log file name. The most recent archived file
		/// always has the number zero.
	{
		int n = -1;
		std::string path;
		do
		{
			path = basePath;
			path.append(".");
			path+=Poco::format("%d",++n);
		}
		while (exists(path));

		return path;
	}
};


} // namespace Poco


#endif // Foundation_ArchiveStrategy_INCLUDED
